<template>
  <div class="teaching-calendar">
    <!-- 教学日历标题 -->
    <h1>教学日历智能生成</h1>

    <!-- 输入开课时间、结课时间和总课时 -->
    <div class="input-group">
      <label for="start_time">开课时间：</label>
      <input
        id="start_time"
        v-model="start_time"
        type="date"
        placeholder="请选择开课时间"
      />
    </div>

    <div class="input-group">
      <label for="end_time">结课时间：</label>
      <input
        id="end_time"
        v-model="end_time"
        type="date"
        placeholder="请选择结课时间"
      />
    </div>

    <div class="input-group">
      <label for="total_time">总学时：</label>
      <input
        id="total_time"
        v-model="total_time"
        type="number"
        placeholder="请输入总学时，如（32）"
      />
    </div>

    <!-- 周上课频次 -->
    <div class="input-group">
      <label for="week_frequency">周上课频次：</label>
      <el-select
        id="week_frequency"
        v-model="week_frequency"
        multiple
        placeholder="请选择周上课频次"
        style="width: 200px"
      >
        <el-option
          v-for="day in weekOptions"
          :key="day"
          :label="day"
          :value="day"
        ></el-option>
      </el-select>
    </div>

    <!-- 智能生成按钮 -->
    <el-button
      type="primary"
      @click="generateTeachingCalendar"
      class="generate-button"
    >
      智能生成教学日历
    </el-button>

    <!-- 显示生成的教学日历表格 -->
    <div v-if="teachingCalendar.length > 0" class="calendar-display">
      <h2>生成的教学日历：</h2>
      <table class="calendar-table">
        <thead>
        <tr>
          <th>校历周次</th>
          <th>授课日期</th>
          <th>授课时数</th>
          <th>主要教学内容</th>
          <th>教学形式及手段</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(row, index) in teachingCalendar" :key="index">
          <td>
            <div class="editable-cell">
              <span v-if="!row.editing" @click="enableEdit(row, 'schoolWeek')">{{ row.schoolWeek }}</span>
              <input
                v-if="row.editing === 'schoolWeek'"
                v-model="row.schoolWeek"
                @blur="disableEdit(row)"
                @keyup.enter="disableEdit(row)"
                class="editable-input"
              />
            </div>
          </td>
          <td>
            <div class="editable-cell">
              <span v-if="!row.editing" @click="enableEdit(row, 'date')">{{ row.date }}</span>
              <input
                v-if="row.editing === 'date'"
                v-model="row.date"
                type="date"
                @blur="disableEdit(row)"
                @keyup.enter="disableEdit(row)"
                class="editable-input"
              />
            </div>
          </td>
          <td>
            <div class="editable-cell">
              <span v-if="!row.editing" @click="enableEdit(row, 'hours')">{{ row.hours }}</span>
              <input
                v-if="row.editing === 'hours'"
                v-model="row.hours"
                @blur="disableEdit(row)"
                @keyup.enter="disableEdit(row)"
                class="editable-input"
              />
            </div>
          </td>
          <td>
            <div class="editable-cell">
              <span v-if="!row.editing" @click="enableEdit(row, 'content')">{{ row.content }}</span>
              <input
                v-if="row.editing === 'content'"
                v-model="row.content"
                @blur="disableEdit(row)"
                @keyup.enter="disableEdit(row)"
                class="editable-input"
              />
            </div>
          </td>
          <td>
            <div class="editable-cell">
              <span v-if="!row.editing" @click="enableEdit(row, 'method')">{{ row.method }}</span>
              <input
                v-if="row.editing === 'method'"
                v-model="row.method"
                @blur="disableEdit(row)"
                @keyup.enter="disableEdit(row)"
                class="editable-input"
              />
            </div>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 显示加载状态 -->
    <div v-if="loadingTeachingCalendar" class="loading-indicator">
      <el-spinner size="small"></el-spinner> 正在生成...
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      start_time: "", // 开课时间
      end_time: "", // 结课时间
      total_time: "", // 总课时
      week_frequency: [], // 周上课频次
      weekOptions: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"], // 周选项
      teachingCalendar: [], // 存储解析后的教学日历内容
      loadingTeachingCalendar: false, // 控制加载状态
    };
  },
  methods: {
    // 调用后端接口生成教学日历
    async generateTeachingCalendar() {
      if (!this.start_time || !this.end_time || !this.total_time || !this.week_frequency.length) {
        this.$message.error("请先填写开课时间、结课时间、总课时和周上课频次！");
        return;
      }
      // 清空之前生成的教学日历内容
      this.teachingCalendar = [];
      this.loadingTeachingCalendar = true;


      try {
        const savedContent = localStorage.getItem("courseOutlineContent");

        if (!savedContent) {
          this.$message.error("未找到保存的课程大纲内容，请先保存！");
          this.loadingTeachingCalendar = false;
          return;
        }

        const requestData = {
          inputs: {
            start_time: this.start_time,
            end_time: this.end_time,
            total_time: this.total_time,
            week: this.week_frequency.join(","),
            directory: savedContent,
          },
          response_mode: "blocking",
          user: "abc-123",
        };

        const response = await axios.post(
          "http://10.109.119.86:8080/v1/workflows/run",
          requestData,
          {
            headers: {
              Authorization: "Bearer app-HZUhLD9PaOmfUTfW0ChzxZ7K",
            },
          }
        );

        if (
          response.data &&
          response.data.data &&
          response.data.data.outputs &&
          response.data.data.outputs.answer
        ) {
          const markdownData = response.data.data.outputs.answer;
          this.teachingCalendar = this.parseTeachingCalendarData(markdownData);
          this.$message.success("教学日历生成成功！");
        } else {
          this.$message.error("教学日历生成失败，请重试！");
        }
      } catch (error) {
        console.error("教学日历智能生成失败", error);
        this.$message.error("生成失败，请稍后再试！");
      } finally {
        this.loadingTeachingCalendar = false;
      }
    },

    parseTeachingCalendarData(answer) {
      try {
        // 将 JSON 字符串解析为对象数组
        const parsedData = JSON.parse(answer);

        // 遍历解析后的数据并映射为前端需要的格式
        return parsedData.map(item => ({
          schoolWeek: item["周次"], // 对应后端的 "周次"
          date: item["授课日期"], // 对应后端的 "授课日期"
          hours: item["授课时数"], // 对应后端的 "授课时数"
          content: item["授课内容"], // 对应后端的 "授课内容"
          method: item["授课方式"], // 对应后端的 "授课方式"
          editing: null, // 默认不处于编辑状态
        }));
      } catch (error) {
        console.error("解析教学数据时出错: ", error);
        return []; // 发生错误时返回空数组
      }
    },

    // 启用编辑模式
    enableEdit(row, field) {
      row.editing = field;
    },

    // 退出编辑模式
    disableEdit(row) {
      row.editing = null;
    },
  },
};
</script>

<style scoped>
.editable-cell {
  position: relative;
}

.editable-input {
  width: 100%;
  border: 1px solid #ccc;
  padding: 4px;
  border-radius: 4px;
  box-sizing: border-box;
}

.calendar-table th,
.calendar-table td {
  border: 1px solid #ddd;
  padding: 25px 25px; /* 增加单元格内边距 */
  text-align: center;
}

.calendar-table tr {
  line-height: 1.8; /* 增加行高 */
}

.calendar-table th {
  background-color: #f0f0f0;
  font-weight: bold;
}

.calendar-table {
  width: 100%;
  border-collapse: collapse; /* 避免双边框效果 */
  margin-top: 10px;
}

</style>
